import re
from base.logcontrol import logger
from functools import singledispatch

"""
提取接口返回模板
"""


def dispatcher(target_index, resource, key, start_tp=None, end_tp=None):
    return extract(target_index,
                   resource,
                   key,
                   start_tp,
                   end_tp)


@singledispatch
def extract(target_index, resource, key, start_tp=None, end_tp=None):
    logger.error(f"\n\tkey:{key},下标不是int或list，target_index:{target_index}\n")
    return {}


@extract.register(int)
def _(target_index, resource, key, start_tp=None, end_tp=None):
    """
    提取资源中的指定下标元素(按“|”分割，只保留“:”左侧)
    :param resource: 资源字典，见get_resource
    :param key: 提取文档的key
    :param target_index: 提取下标，数字或列表
    :param start_tp: 按前缀查找
    :param end_tp: 按后缀查找
    :return:{key:模板提取资源集合(提取的target_index元素集合mix)}
    """
    ret = set()
    if key not in resource:
        return {key: None}

    regex = re.compile("^[a-zA-Z]+.*")

    for child in resource[key]:

        # 过滤disable为true
        if child[-1].lower() == "true":
            continue

        # 处理含有“|”的项
        for elm in child[target_index].split("|"):
            if not re.search(regex, elm):
                continue

            # 只保留“：”左部
            element = elm.split(":")[0]

            # 根据项的开头和结尾字符过滤
            if start_tp:
                if element.startswith(start_tp):
                    ret.add(element)
                continue
            if end_tp:
                if element.endswith(end_tp):
                    ret.add(element)
                continue
            ret.add(element)
    return {key: ret}


@extract.register(list)
def _(target_index, resource, key, start_tp=None, end_tp=None):
    if not target_index:
        logger.warning(f"\n\tkey:{key},target_index为空\n")
        return {}
    ret = set()
    if key not in resource:
        return {key: None}

    regex = re.compile("^[a-zA-Z]+.*")

    for child in resource[key]:
        if child[-1].lower() == "true":
            continue
        for idx in target_index:
            for elm in child[idx].split("|"):
                if not re.search(regex, elm):
                    continue
                element = elm.split(":")[0]
                if start_tp:
                    if element.startswith(start_tp):
                        ret.add(element)
                    continue
                if end_tp:
                    if element.endswith(end_tp):
                        ret.add(element)
                    continue
                ret.add(element)
    return {key: ret}
